package fu.k4c.vTeam.Login;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Main.MainActivity;
import fu.k4c.vTeam.Object.Account;
import fu.k4c.vTeam.Object.User;

public class LoginActivity extends Activity {
	Account data;
	ProgressDialog proDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		final EditText et_user = (EditText) findViewById(R.id.et_login_acc);
		final EditText et_pass = (EditText) findViewById(R.id.et_login_pass);
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
		Button btn_back = (Button) findViewById(R.id.btn_login_back);
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		final CheckBox cb_remember = (CheckBox) findViewById(R.id.cb_login_remember);
		final SharedPreferences app_preference = PreferenceManager
				.getDefaultSharedPreferences(this);
		Button btn_login = (Button) findViewById(R.id.btn_login_submit);
		btn_login.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AsyncTask<Void, Void, Void>() {
					Account acc;
					User user;
					boolean tmp = false;;

					@Override
					protected Void doInBackground(Void... params) {
						// TODO Auto-generated method stub
									try {
										if (cb_remember.isChecked()) {

											SharedPreferences.Editor editor = app_preference
													.edit();
											editor.putString("Check", "Check");
											editor.putString("user", et_user
													.getText().toString());
											editor.putString("pass", et_pass
													.getText().toString());
											editor.commit();
										}
										SchemeRegistry registry = new SchemeRegistry();
										registry.register(new Scheme("http",
												PlainSocketFactory
														.getSocketFactory(), 80));
										HttpParams httpParams = new BasicHttpParams();
										ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
												httpParams, registry);
										HttpClient client = new DefaultHttpClient(
												connMgr, httpParams);
										HttpPost post = new HttpPost(
												getString(R.string.connectionString)
														+ "vLocationService/login");
										post.setHeader("Accept",
												"application/json");
										post.setHeader("Content-type",
												"application/json");
										HashMap<String, Object> postParameters = new HashMap<String, Object>();
										user = new User(et_user.getText()
												.toString(),
												encryptPassword(et_pass
														.getText().toString()));
										postParameters.put("UserName",
												user.getUsername());
										postParameters.put("Password",
												user.getPassword());
										Gson gson = new Gson();
										String jsonParameters = gson
												.toJson(postParameters);
										// Toast.makeText(getApplicationContext(),jsonParameters,
										// Toast.LENGTH_LONG).show();
										post.setEntity(new StringEntity(
												jsonParameters));
										HttpResponse response = client
												.execute(post);

										HttpEntity entity = response
												.getEntity();
										String jsonresult = EntityUtils
												.toString(entity);
										acc = gson.fromJson(jsonresult,
												Account.class);

									} catch (Exception e) {
										// TODO: handle exception
										tmp = true;
									}

						return null;
					}

					protected void onPostExecute(Void result) {

						proDialog.dismiss();
						if(tmp)
						{
							Toast.makeText(
									getApplicationContext(),
									"Bạn vui lòng kiểm tra lại kết nối Internet",
									Toast.LENGTH_SHORT).show();
						}
						else
						{
							try {

								if (acc.getStatus().equals("False")) {
									Toast.makeText(
											getApplicationContext(),
											"Bạn đã nhập sai tài khoản hoặc mật khẩu",
											Toast.LENGTH_LONG).show();
								} else {
									Intent i = new Intent(LoginActivity.this,
											MainActivity.class);
									i.putExtra("status", acc.getStatus());
									i.putExtra("email", user.getUsername());
									i.putExtra("fullName", acc.getFullName());
									startActivity(i);
								}
							} catch (Exception e) {
								// TODO: handle exception
								Toast.makeText(getApplicationContext(),
										"Xin vui lòng thử lại", Toast.LENGTH_SHORT)
										.show();
							}
						}
						

					};

					protected void onPreExecute() {
						proDialog = new ProgressDialog(LoginActivity.this);
						proDialog.setMessage("Đang kết nối đến máy chủ...");
						proDialog.setCancelable(false);
						proDialog.show();
					};

					protected void onProgressUpdate(Void... values) {
					}

				}.execute();

			}
		});
		Button btn_regis = (Button) findViewById(R.id.btn_login_regis);
		btn_regis.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(LoginActivity.this, RegisActivity.class);
				startActivity(i);

			}
		});
		Button btn_forgot = (Button) findViewById(R.id.btn_login_fogot);
		btn_forgot.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(LoginActivity.this,
						LoginFogotPassword.class);
				startActivity(i);
			}
		});

		String temp = app_preference.getString("Check", "Uncheck");
		if (temp.equals("Check")) {
			cb_remember.setChecked(true);
		} else {
			cb_remember.setChecked(false);
		}
		if (cb_remember.isChecked()) {
			String user = app_preference.getString("user", "");
			String pass = app_preference.getString("pass", "");
			et_user.setText(user);
			et_pass.setText(pass);

		}
		cb_remember.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (cb_remember.isChecked()) {

					SharedPreferences.Editor editor = app_preference.edit();
					editor.putString("Check", "Check");
					editor.putString("user", et_user.getText().toString());
					editor.putString("pass", et_pass.getText().toString());
					editor.commit();
					// Toast.makeText(getApplicationContext(),
					// tv_user.getText().toString(), Toast.LENGTH_LONG).show();
				} else {
					cb_remember.setChecked(false);
					SharedPreferences.Editor editor = app_preference.edit();
					editor.putString("Check", "UnCheck");
					editor.putString("user", "");
					editor.putString("pass", "");
					editor.commit();
					// Toast.makeText(getApplicationContext(), "Uncheck",
					// Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	private static String encryptPassword(String password) {
		String sha1 = "";
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(password.getBytes("UTF-8"));
			sha1 = byteToHex(crypt.digest());
			sha1 = sha1.toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sha1;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		return formatter.toString();
	}

}
